// pages/merchant/device-management/index.js
const { FormUtils } = require('../../../utils/form-config.js');
const apiService = require('../../../utils/api.js');

Page({
  data: {
    devices: [],
    filteredDevices: [],
    searchKeyword: '',
    showModal: false,
    showControlModal: false,
    showDeleteModal: false,
    isEdit: false,
    formData: {},
    isFormValid: false,
    selectedDevice: null,
    durationIndex: 0,
    durationOptions: [
      { label: '15分钟', value: 15 },
      { label: '30分钟', value: 30 },
      { label: '45分钟', value: 45 },
      { label: '60分钟', value: 60 }
    ],
    deviceStats: {
      total: 0,
      online: 0,
      inUse: 0,
      offline: 0
    }
  },

  onLoad() {
    this.loadDevices();
  },

  onShow() {
    this.loadDevices();
  },

  // 加载设备列表
  async loadDevices() {
    try {
      wx.showLoading({ title: '加载中...' });
      
      // 获取门店ID（从缓存中获取选中的门店，超级管理员已选择门店，普通用户使用默认门店）
      const storeId = wx.getStorageSync('selectedStoreId') || wx.getStorageSync('currentStoreId') || 'default_store';
      
      // 调用真实的API获取设备列表
      const result = await apiService.callFunction('admin', 'device/list', {
        storeId: storeId,
        page: 1,
        size: 100
      });
      
      if (result.code === 200 && result.data && result.data.list) {
        const devices = result.data.list;
        
        // 转换设备数据格式
        const processedDevices = devices.map(device => ({
          _id: device._id,
          name: device.name,
          status: this.mapStatusToEnum(device.status),
          type: device.type,
          code: device.code || device._id,
          category: this.getCategoryText(device.category || device.type),
          location: this.parseLocation(device.location),
          price: device.price || 0,
          displayPriceYuan: (device.price || 0) / 100, // 后端为分，转为元
          mqttConfig: {
            appId: device.appId,
            deviceKey: device.deviceKey,
            deviceMAC: device.deviceMAC,
            publishTopic: device.publishTopic || ''
          }
        }));
        
        // 计算统计数据
        const stats = {
          total: processedDevices.length,
          online: processedDevices.filter(d => d.status === 'AVAILABLE').length,
          inUse: processedDevices.filter(d => d.status === 'IN_USE').length,
          offline: processedDevices.filter(d => d.status === 'OFFLINE' || d.status === 'MAINTENANCE').length
        };
        
        this.setData({
          devices: processedDevices,
          filteredDevices: processedDevices,
          deviceStats: stats
        });
      } else {
        throw new Error(result.msg || '获取设备列表失败');
      }
      
      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '加载失败: ' + (error.message || '未知错误'),
        icon: 'none',
        duration: 3000
      });
      console.error('加载设备失败:', error);
    }
  },

  // 映射状态到枚举
  mapStatusToEnum(status) {
    const statusMap = {
      0: 'MAINTENANCE',
      1: 'AVAILABLE',
      2: 'IN_USE',
      3: 'OFFLINE'
    };
    return statusMap[status] || 'UNKNOWN';
  },

  // 获取分类文本
  getCategoryText(category) {
    const categoryMap = {
      'bath': '洗浴',
      'dryer': '烘干',
      'grooming': '美容',
      'door': '门禁',
      'blow': '吹水'
    };
    return categoryMap[category] || category || '其他';
  },

  // 解析位置信息
  parseLocation(location) {
    if (typeof location === 'string') {
      return { room: location, position: '' };
    } else if (location && typeof location === 'object') {
      return location;
    }
    return { room: '', position: '' };
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });
    this.filterDevices(keyword);
  },

  // 过滤设备
  filterDevices(keyword) {
    const { devices } = this.data;
    const filtered = devices.filter(device => 
      device.name.toLowerCase().includes(keyword.toLowerCase()) ||
      device.code.toLowerCase().includes(keyword.toLowerCase()) ||
      device.category.toLowerCase().includes(keyword.toLowerCase())
    );
    this.setData({ filteredDevices: filtered });
  },

  // 添加设备
  onAddDevice() {
    const formData = FormUtils.initFormData('deviceInfo');
    this.setData({
      showModal: true,
      isEdit: false,
      formData,
      isFormValid: false
    });
  },

  // 编辑设备
  onEditDevice(e) {
    const item = e.currentTarget.dataset.item;
    const formData = { ...item };
    
    this.setData({
      showModal: true,
      isEdit: true,
      formData,
      selectedDevice: item,
      isFormValid: true
    });
  },

  // 控制设备
  onControlDevice(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      showControlModal: true,
      selectedDevice: item,
      durationIndex: 0
    });
  },

  // 删除设备
  onDeleteDevice(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      showDeleteModal: true,
      selectedDevice: item
    });
  },

  // 确认删除
  async onConfirmDelete() {
    const { selectedDevice } = this.data;
    
    try {
      wx.showLoading({ title: '删除中...' });
      
      // 调用真实API
      const result = await apiService.callFunction('admin', 'device/delete', {
        deviceId: selectedDevice._id
      });
      
      if (result.code === 200) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        
        // 重新加载设备列表
        await this.loadDevices();
        
        this.onCloseDeleteModal();
      } else {
        throw new Error(result.msg || '删除失败');
      }
      
      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '删除失败: ' + (error.message || '未知错误'),
        icon: 'none',
        duration: 3000
      });
      console.error('删除失败:', error);
    }
  },

  // 启动设备
  async onStartDevice() {
    const { selectedDevice, durationIndex, durationOptions } = this.data;
    const duration = durationOptions[durationIndex].value;
    
    try {
      wx.showLoading({ title: '启动中...' });
      
      // 调用真实API控制设备（商家端页面，无需传isAdmin参数）
      const result = await apiService.callFunction('device', 'controlDevice', {
        deviceId: selectedDevice._id,
        action: 'on',
        duration: duration
      });
      
      if (result.success) {
        wx.showToast({
          title: '设备启动成功',
          icon: 'success'
        });
        
        // 重新加载设备列表
        await this.loadDevices();
        
        this.onCloseControlModal();
      } else {
        throw new Error(result.message || '启动失败');
      }
      
      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '启动失败: ' + (error.message || '未知错误'),
        icon: 'none',
        duration: 3000
      });
      console.error('启动设备失败:', error);
    }
  },

  // 停止设备
  async onStopDevice() {
    const { selectedDevice } = this.data;
    
    try {
      wx.showLoading({ title: '停止中...' });
      
      // 调用真实API控制设备（商家端页面，无需传isAdmin参数）
      const result = await apiService.callFunction('device', 'controlDevice', {
        deviceId: selectedDevice._id,
        action: 'off'
      });
      
      if (result.success) {
        wx.showToast({
          title: '设备停止成功',
          icon: 'success'
        });
        
        // 重新加载设备列表
        await this.loadDevices();
        
        this.onCloseControlModal();
      } else {
        throw new Error(result.message || '停止失败');
      }
      
      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '停止失败: ' + (error.message || '未知错误'),
        icon: 'none',
        duration: 3000
      });
      console.error('停止设备失败:', error);
    }
  },

  // 选择时长
  onSelectDuration(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ durationIndex: index });
  },

  // 表单数据变化
  onFormChange(e) {
    const { formData } = e.detail;
    this.setData({ formData });
  },

  // 表单验证
  onFormValidate(e) {
    const { isValid } = e.detail;
    this.setData({ isFormValid: isValid });
  },

  // 确认保存
  async onConfirmSave() {
    if (!this.data.isFormValid) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'error'
      });
      return;
    }

    try {
      wx.showLoading({ title: '保存中...' });
      
      const { formData, isEdit, selectedDevice } = this.data;
      const storeId = wx.getStorageSync('currentStoreId') || 'default_store';
      
      let result;
      if (isEdit) {
        // 编辑模式 - 调用更新API
        result = await apiService.callFunction('admin', 'device/update', {
          deviceId: selectedDevice._id,
          ...formData,
          storeId: storeId
        });
      } else {
        // 添加模式 - 调用添加API
        result = await apiService.callFunction('admin', 'device/add', {
          ...formData,
          storeId: storeId
        });
      }
      
      if (result.code === 200) {
        wx.showToast({
          title: isEdit ? '编辑成功' : '添加成功',
          icon: 'success'
        });
        
        // 重新加载设备列表
        await this.loadDevices();
        
        this.onCloseModal();
      } else {
        throw new Error(result.msg || '保存失败');
      }
      
      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '保存失败: ' + (error.message || '未知错误'),
        icon: 'none',
        duration: 3000
      });
      console.error('保存失败:', error);
    }
  },

  // 关闭弹窗
  onCloseModal() {
    this.setData({
      showModal: false,
      formData: {},
      isFormValid: false,
      selectedDevice: null
    });
  },

  // 关闭控制弹窗
  onCloseControlModal() {
    this.setData({
      showControlModal: false,
      selectedDevice: null,
      durationIndex: 0
    });
  },

  // 关闭删除确认弹窗
  onCloseDeleteModal() {
    this.setData({
      showDeleteModal: false,
      selectedDevice: null
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 一键开启所有设备
  async onStartAllDevices() {
    wx.showModal({
      title: '确认开启',
      content: '确定要开启所有设备吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '正在开启所有设备...' });
            
            const { devices } = this.data;
            const storeId = wx.getStorageSync('currentStoreId') || 'default_store';
            
            // 批量控制所有设备
            let successCount = 0;
            let failCount = 0;
            
            for (const device of devices) {
              try {
                const result = await apiService.callFunction('device', 'controlDevice', {
                  deviceId: device._id,
                  action: 'on',
                  duration: 30 // 默认30分钟
                });
                
                if (result.success) {
                  successCount++;
                } else {
                  failCount++;
                }
              } catch (error) {
                failCount++;
                console.error(`设备 ${device.name} 开启失败:`, error);
              }
            }
            
            wx.hideLoading();
            
            wx.showToast({
              title: `成功: ${successCount}, 失败: ${failCount}`,
              icon: failCount > 0 ? 'none' : 'success',
              duration: 3000
            });
            
            // 重新加载设备列表
            await this.loadDevices();
          } catch (error) {
            wx.hideLoading();
            wx.showToast({
              title: '批量开启失败',
              icon: 'error'
            });
            console.error('批量开启设备失败:', error);
          }
        }
      }
    });
  },

  // 一键关闭所有设备
  async onStopAllDevices() {
    wx.showModal({
      title: '确认关闭',
      content: '确定要关闭所有设备吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '正在关闭所有设备...' });
            
            const { devices } = this.data;
            
            // 批量控制所有设备
            let successCount = 0;
            let failCount = 0;
            
            for (const device of devices) {
              try {
                const result = await apiService.callFunction('device', 'controlDevice', {
                  deviceId: device._id,
                  action: 'off'
                });
                
                if (result.success) {
                  successCount++;
                } else {
                  failCount++;
                }
              } catch (error) {
                failCount++;
                console.error(`设备 ${device.name} 关闭失败:`, error);
              }
            }
            
            wx.hideLoading();
            
            wx.showToast({
              title: `成功: ${successCount}, 失败: ${failCount}`,
              icon: failCount > 0 ? 'none' : 'success',
              duration: 3000
            });
            
            // 重新加载设备列表
            await this.loadDevices();
          } catch (error) {
            wx.hideLoading();
            wx.showToast({
              title: '批量关闭失败',
              icon: 'error'
            });
            console.error('批量关闭设备失败:', error);
          }
        }
      }
    });
  }
});